/**
 * 精确小数(目标小数位数小于最大精确位数直接返回原值，否则在精确位数+1上四舍五入)
 * @param {Number} num 待精确小数
 * @param {Number} min 最小位数
 * @param {Number} max 最大位数
 */
export const toFixeds = (num: number | string, min?: number, max?: number): string => {
  const minFix = min || 2;
  const maxFix = max;
  let str = String(num).replace(/^-/, '');
  if (maxFix && maxFix < minFix) {
    return `${num}`;
  }
  const prefixSymbol = String(num).startsWith('-') ? '-' : '';
  const dotIndex = str.indexOf('.');
  if (dotIndex === -1) {
    let dotArr = '.';
    for (let i = 0; i < minFix; i++) {
      dotArr += '0';
    }
    return str + dotArr;
  }
  const maxLen = maxFix || minFix;
  let i = dotIndex + 1;
  let n = '';
  while (n.length < maxLen) {
    n += (str[i++] || '0') + '';
    if (!str[i] && n.length >= minFix) {
      break;
    }
  }

  const newStr = str.substring(0, dotIndex) + '.' + n;
  let step = 0; //四舍五入进位
  if (i < str.length) {
    step = Number(str[i]) >= 5 ? 1 : 0;
  }
  const nums = newStr.split('');
  const numberNums = nums.map(item => (item === '.' ? '.' : Number(item)));
  if (step > 0) {
    while (i > 0) {
      i--;
      if (numberNums[i] === '.') {
        continue;
      }
      const sum = Number(numberNums[i]) + Number(step);
      numberNums[i] = sum % 10;
      step = sum >= 10 ? 1 : 0;
      if (i === 0 && Number(numberNums[i]) === 0) {
        numberNums.splice(0, 0, 1);
      }
      if (step === 0) break;
    }
  }
  return `${prefixSymbol}` + numberNums.join('');
};
